package com.goalias.service.impl;

import com.goalias.constant.SystemConstants;
import com.goalias.domain.entity.Notice;
import com.goalias.domain.dto.EmailDto;
import com.goalias.mapper.NoticeMapper;
import com.goalias.service.INoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goalias.util.EmailUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 通知记录表 服务实现类
 * </p>
 *
 * @author goalias
 * @since 2024-12-18
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    @Resource
    private EmailUtil emailUtil;
    private static final Map<String, LocalDateTime> map = new HashMap<>();

    @Override
    public void sendMail(EmailDto emailDto) {
        emailUtil.sendSimpleMail(emailDto.getTo(), emailDto.getSubject(), emailDto.getContent());
        Notice notice = new Notice();
        notice.setType(emailDto.getType())
                .setScene(emailDto.getScene())
                .setDescription(emailDto.getDescription());
        save(notice);
    }

    @Override
    public void sendWarningMail(String className, String methodName, String systemWarnType) {
        String key = className + "->" + methodName;
        if (!map.containsKey(key) || LocalDateTime.now().minusSeconds(SystemConstants.FALLBACK_TIMEOUT).isAfter(map.get(key))) {
            synchronized (NoticeServiceImpl.class) {
                if (map.containsKey(key)) {
                    return;
                }
                map.put(key, LocalDateTime.now());
                emailUtil.sendHtmlMail(SystemConstants.TO_EMAIL, systemWarnType, emailUtil.warningTemplate(className, methodName, systemWarnType));
                Notice notice = new Notice();
                notice.setType(SystemConstants.WARNING_TYPE)
                        .setScene(SystemConstants.warnNoticeMap.get(systemWarnType))
                        .setDescription(systemWarnType+"->"+className+"->"+methodName);
                save(notice);
            }
        }

    }

}
